package com.zjj.lbw.designpattern.singleton;

/**
 * @author zhanglei.zjj
 * @description 静态内部类方式实现 懒汉单例模式
 * @date 2023/7/11 17:49
 */
public class InnerClassLazySingletonTest {
    public static void main(String[] args) {
        InnerClassLazySingleton instance1 = InnerClassLazySingleton.getInstance();
        System.out.println(instance1);
        InnerClassLazySingleton instance2 = InnerClassLazySingleton.getInstance();
        System.out.println(instance2);
    }
}

class InnerClassLazySingleton {

    static {
        System.out.println(" InnerClassSingleton "); //  1
    }

    private InnerClassLazySingleton() {

        if (LazySingletonHolder.instance != null) {
            throw new RuntimeException(" 不允许多个实例。");
        }

    }

    public static InnerClassLazySingleton getInstance() {
        // 内部类只有使用时候才会去加载，这就是实现了懒加载
        return LazySingletonHolder.instance;
    }


    private static class LazySingletonHolder {
        private static InnerClassLazySingleton instance = new InnerClassLazySingleton();

        static {
            System.out.println(" SingletonHolder ");// 2
        }
    }

}
